<?php
namespace app\api\controller\transit;

use app\api\controller\Base;
use app\common\model\orderdata\Goods;
use app\common\model\power\Rolepower;
use app\common\model\transit\Transitcompany as Trancompany;
use app\common\model\transit\TransitDriver;
use app\common\model\transit\TransitUser;
use app\common\model\transit\Transport;
use app\common\model\transit\TransitEscort;
use app\common\model\user\User as UserModel;
use think\facade\Env;
use think\File;

class Transitmana extends Base
{

    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(106001);
    }

    public function gettransport()
    {
        $data['order'] = 'TranSportId ase';
        $data          = Transport::usergetlist($data);
        return myok($data);
    }
    public function addtransport()
    {
        $id   = input('TransportId');
        $data = input('post.');
        if (!empty($id)) {
            $data = Transport::user_reinfo($id, $data);
            return myok($id);
        } else {
            $data = Transport::user_create($data);
            return myok($data);
        }
    }


    /**
     * 添加收集员
     * @return [type] [description]
     */
    public function adduser()
    {
        $data = input('post.');
        if (empty($data['UserTel'])) {
            return myerr('请输入联系方式');
        }

        if (empty($data['UserName'])) {
            return myerr('请输入收集员姓名');
        }
       
       	$comp = Trancompany::user_getinfo();
       	//创建一个用户账号名称以司机名为准
       	$userid = UserModel::user_createuser($data['UserTel'], 107, $data['UserName']);
       	//检测关系是否存在
       	$sb = TransitUser::where('UserId',$userid)->where('TransitCompanyId',$comp['TransitCompanyId'])->find();
       	if(!empty($sb)){
       		return myerr('关系已存在无需再次绑定');
       	}
       	//创建一个绑定关系
       	$ts                   = new TransitUser();
       	$ts->UserId           = $userid;
       	$ts->TransitCompanyId = $comp['TransitCompanyId'];
       	$ts->save();

	   	return myok($ts->TransitUserId);
    }

    /**
     * 与用户解除关系
     * @return [type] [description]
     */
    public function deluser(){
    	$id = input('id');
    	if(empty($id)){
    		return moerr('缺少重要参数');
    	}
    	$sb = TransitUser::get($id);
    	if(empty($sb)){
    		return moerr('没有找到此收集员信息');
    	}
    	//判断权限
    	$comp = Trancompany::user_getinfo();
    	if($comp['TransitCompanyId']!==$sb['TransitCompanyId']){
    		return moerr('没有权限');
    	}
    	//删除此驾驶员信息
    	$sb->delete();
    	return myok('解除成功');
    }
    /**
     * 添加司机
     * @return [type] [description]
     */
    public function addescort()
    {
        $id   = input('TransitEscortId');
        $data = input('post.');
        if (empty($data['UserTel'])) {
            return myerr('请输入联系方式');
        }

        if (empty($data['UserName'])) {
            return myerr('请输入押运员姓名');
        }
        //将司机添加为收集员
        if ((!empty($data['BindUser'])) && $data['BindUser'] == 'true') {
            $comp = Trancompany::user_getinfo();
            //创建一个用户账号名称以司机名为准
            $userid = UserModel::user_createuser($data['UserTel'], 107, $data['UserName']);
            //检测关系是否存在
            $sb = TransitUser::where('UserId',$userid)->where('TransitCompanyId',$comp['TransitCompanyId'])->find();
            if(!empty($sb)){
                return myerr('关系已存在无需再次绑定');
            }
            //创建一个绑定关系
            $ts                   = new TransitUser();
            $ts->UserId           = $userid;
            $ts->TransitCompanyId = $comp['TransitCompanyId'];
            $ts->save();
        }

        if (!empty($id)) {
            $data = TransitEscort::user_reinfo($id, $data);
            return myok($id);
        } else {
            $data = TransitEscort::user_create($data);
            return myok($data);
        }
    }

    /**
     * 添加司机
     * @return [type] [description]
     */
    public function adddriver()
    {
        $id   = input('TransitDriverId');
        $data = input('post.');
        if (empty($data['UserTel'])) {
            return myerr('请输入联系方式');
        }

        if (empty($data['UserName'])) {
            return myerr('请输入司机姓名');
        }
        //将司机添加为收集员
        if ((!empty($data['BindUser'])) && $data['BindUser'] == 'true') {
            $comp = Trancompany::user_getinfo();
            //创建一个用户账号名称以司机名为准
            $userid = UserModel::user_createuser($data['UserTel'], 107, $data['UserName']);
            //检测关系是否存在
            $sb = TransitUser::where('UserId',$userid)->where('TransitCompanyId',$comp['TransitCompanyId'])->find();
            if(!empty($sb)){
            	return myerr('关系已存在无需再次绑定');
            }
            //创建一个绑定关系
            $ts                   = new TransitUser();
            $ts->UserId           = $userid;
            $ts->TransitCompanyId = $comp['TransitCompanyId'];
            $ts->save();
        }

        if (!empty($id)) {
            $data = TransitDriver::user_reinfo($id, $data);
            return myok($id);
        } else {
            $data = TransitDriver::user_create($data);
            return myok($data);
        }
    }

    /**
     * 删除司机信息，当收集员有此司机信息时将询问是否一起删除
     * @return [type] [description]
     */
    public function delescort()
    {
        $id = input('id');
        $data = input('post.');
        $confirm = input('confirm');
        if(empty($id)){
            return moerr('缺少重要参数');
        }
        $sb = TransitEscort::get($id);
        if(empty($sb)){
            return moerr('没有找到此押运员信息');
        }
        //判断权限
        $comp = Trancompany::user_getinfo();
        if($comp['TransitCompanyId']!==$sb['TransitCompanyId']){
            return moerr('没有权限');
        }
        if(empty($confirm) || $confirm=='false'){
            //判断此手机号是否与该运输单位存在关联
            //查询是否存在此手机号
            $usb = UserModel::iphone_state($sb['UserTel']);
            if($usb['code']){
                //查询此手机号是否与公司有关联收集员信息
                $ts = TransitUser::where('UserId',$usb['msg'])->where('TransitCompanyId',$sb['TransitCompanyId'])->find();
                if(!empty($ts)){
                    //查询此手机号是否是驾驶员
                    $ts = TransitDriver::where('UserId',$usb['msg'])->where('TransitCompanyId',$sb['TransitCompanyId'])->find();
                    if(empty($ts)){
                        //如果此人是收集员（不是驾驶员）时则提醒是否删除并解除关联关系
                        //只有返回ok 才确认是删除成功
                        return myok('请确认是否删除');
                    }
                }
            }
        }
        //删除此驾驶员信息
        $sb->delete();
        //删除关联信息
        if(!empty($confirm) && $confirm=='true'){
            $usb = UserModel::iphone_state($sb['UserTel']);
            TransitUser::where('UserId',$usb['msg'])->where('TransitCompanyId',$sb['TransitCompanyId'])->delete();
        }
        return myok('ok');
    }

    /**
     * 删除司机信息，当收集员有此司机信息时将询问是否一起删除
     * @return [type] [description]
     */
    public function deldriver()
    {
    	$id = input('id');
    	$data = input('post.');
    	$confirm = input('confirm');
    	if(empty($id)){
    		return moerr('缺少重要参数');
    	}
    	$sb = TransitDriver::get($id);
    	if(empty($sb)){
    		return moerr('没有找到此司机信息');
    	}
    	//判断权限
    	$comp = Trancompany::user_getinfo();
    	if($comp['TransitCompanyId']!==$sb['TransitCompanyId']){
    		return moerr('没有权限');
    	}
    	if(empty($confirm) || $confirm=='false'){
    		//判断此手机号是否与该运输单位存在关联
    		//查询是否存在此手机号
    		$usb = UserModel::iphone_state($sb['UserTel']);
    		if($usb['code']){
    			//查询此手机号是否与公司有关联收集员信息
    			$ts = TransitUser::where('UserId',$usb['msg'])->where('TransitCompanyId',$sb['TransitCompanyId'])->find();
    			if(!empty($ts)){
                    //查询此手机号是否是押运员
                    $ts = TransitEscort::where('UserId',$usb['msg'])->where('TransitCompanyId',$sb['TransitCompanyId'])->find();
    				if(empty($ts)){
                        //如果此人是不是押运员时则提醒是否删除并解除关联关系
                        //只有返回ok 才确认是删除成功
                        return myok('请确认是否删除');
                    }
    			}
    		}
    	}
    	//删除此驾驶员信息
    	$sb->delete();
    	//删除关联信息
    	if(!empty($confirm) && $confirm=='true'){
    		$usb = UserModel::iphone_state($sb['UserTel']);
			TransitUser::where('UserId',$usb['msg'])->where('TransitCompanyId',$sb['TransitCompanyId'])->delete();
    	}
    	return myok('ok');
    }

    /**
     * 获取关联收集员列表
     * @return [type] [description]
     */
    public function getuserlist(){
    	$data = TransitUser::getlist();
    	return myok($data);
    }

    /**
     * 获取关联驾驶员列表
     * @return [type] [description]
     */
    public function getdriverlist()
    {
        $data['order'] = 'TransitDriverId ase';
        $data          = TransitDriver::usergetlist($data);
        return myok($data);
    }

    /**
     * 获取关联押运员列表
     * @return [type] [description]
     */
    public function getescortlist()
    {
        $data['order'] = 'TransitEscortId ase';
        $data          = TransitEscort::usergetlist($data);
        return myok($data);
    }
    /**
     * 获取企业信息
     * @return [type] [description]
     */
    public function getcompanyinfo()
    {
        $company  = Trancompany::user_getinfo();
        $userdata = UserModel::getinfo();
        //为空则给企业返回修改信息
        if (empty($company['Tel'])) {
            $company['Tel'] = $userdata['Iphone'];
        }
      
        return myok($company);

    }
    public function getgoodlist()
    {
        $goodlist = Goods::getlist();
        return myok($goodlist);
    }
    /**
     * 修改/完善企业信息
     * 产废人信息也再次完善
     * @return [type] [description]
     */
    public function recompanyinfo()
    {
        $data    = input('post.');
        $company = Trancompany::user_getinfo();
        //为空则给企业返回修改信息
        if (empty($data)) {
            return myok($company);
        }
        if (empty($company)) {
            //创建一个企业信息
            $result = $this->validate($data, 'app\common\validate\Transitcompany.companycreate');
            if (true !== $result) {
                return myerr($result);
            }
            $company = Trancompany::user_create($data);
            return myok('企业信息已完善');
        } else {
            //修改企业信息
            $sb = Trancompany::user_reinfo($data);
            return myok('企业信息已修改');
        }
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'transport' || !$type == 'order') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\hawa\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/hawa/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
